//
//  DelCollectionViewController.m
//  WeatherGuide
//
//  Created by lanou3g on 15/12/24.
//  Copyright © 2015年 李明. All rights reserved.
//

#import "DelCollectionViewController.h"
#import "DelCollectionViewCell.h"
#import <CoreData/CoreData.h>
#import "Weather.h"
#import "AppDelegate.h"
#import "ReachCityCollectionViewController.h"
#import "GetWeatherHandle.h"

@interface DelCollectionViewController ()

@property (nonatomic,strong) NSArray *array;

@end

@implementation DelCollectionViewController

static NSString * const reuseIdentifier = @"DelCollectionViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
 
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
    // Register cell classes
   
    [self.collectionView registerNib:[UINib nibWithNibName:reuseIdentifier bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    
    // Do any additional setup after loading the view.
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of items
   self.array = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
     NSLog(@"%ld",self.array.count);
    if (self.array.count == 9) {
        return 9;
    }
    return self.array.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 
    
    
    DelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Weather"];
    if (indexPath.item < self.array.count) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city CONTAINS %@",self.array[indexPath.item]];
        request.predicate = predicate;
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        
        NSArray *arrayWeather = [app.managedObjectContext executeFetchRequest:request error:nil];
        cell.weather = arrayWeather.firstObject;
        
        if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"取消"]) {
            cell.delImageView.image = [UIImage imageNamed:@"iconfont-shanchu.png"];
//            cell.editor = YES;
        }else{
            cell.delImageView.image = nil;
//            cell.editor = NO;
        }
     }else {
        cell.weather = nil;
        cell.addImageView.image = [UIImage imageNamed:@"add.png"];
        cell.delImageView.image = nil;
//        cell.editor = NO;
    }
        cell.backgroundColor = [UIColor lightGrayColor];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.item == self.array.count) {
        
        
        ReachCityCollectionViewController *reachVC = [[ReachCityCollectionViewController alloc] initWithNibName:@"ReachCityCollectionViewController" bundle:[NSBundle mainBundle]];
        UINavigationController *reachNC = [[UINavigationController alloc] initWithRootViewController:reachVC];
        reachVC.array = [[GetWeatherHandle sharedHandle].dicCityInfo allKeys];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DelCollectionViewControllerAction:) name:@"DelCollectionViewController" object:nil];
        [self presentViewController:reachNC animated:YES completion:^{
            reachVC.array = [[GetWeatherHandle sharedHandle].dicCityInfo allKeys];
            
        }];
    }else{
      
        DelCollectionViewCell *cell = (DelCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        if (cell.delImageView.image != nil) {
            NSArray *array =  [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
            NSMutableArray *arrayt = [NSMutableArray arrayWithArray:array];
            NSLog(@"%@",cell.cityLabel.text);
            NSLog(@"arrayt = %@",arrayt);
            [arrayt removeObject:cell.cityLabel.text];
            [[NSUserDefaults standardUserDefaults] setObject:arrayt forKey:@"city"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
//            self.navigationItem.rightBarButtonItem.title = @"编辑";
            [self.collectionView reloadData];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"conllectionViewReloadDataAction" object:nil];
            
        }else{
            [self dismissViewControllerAnimated:NO completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"conllectionViewReloadDataAction" object:cell.cityLabel.text];
            }];
        }
        
       
    }
 
}

- (void)DelCollectionViewControllerAction:(NSNotification *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"conllectionViewReloadDataAction" object:sender.object];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }];
    

}

- (void)rightBarButtonItemAction:(UIBarButtonItem *)sender
{
    if ([sender.title isEqualToString:@"编辑"]) {
        sender.title = @"取消";
    }else{
        sender.title = @"编辑";
    }
    [self.collectionView reloadData];
}



/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
